<?php
header('content-type:text/html;charset=utf-8');
#error_reporting(E_ERROR | E_PARSE);
date_default_timezone_set('PRC');

define('ROOT_DIR', dirname(__FILE__));
define('LOG_DIR', ROOT_DIR . '/logs/');
define('DEBUG_MODE', true);
define('CACHE_KEY_PREFIX', '');

require(ROOT_DIR . '/vendor/autoload.php');
require(ROOT_DIR . '/includes/autoload.php');
require(ROOT_DIR . '/includes/config.php');
require(ROOT_DIR . '/includes/function.php');

try {
    $cmd = $argv[1] ?? 'start';
    switch ($cmd) {
        case 'start':
            Swoole\Runtime::enableCoroutine();
            new App\Index;
            break;
        case 'stop':
            try {
                $client = new swoole_client(SWOOLE_SOCK_TCP);
                $cnf    = getConfig();
                if (!$client->connect($cnf->swoole->host, $cnf->swoole->port, -1)) {
                    throw new Exception("connect failed. Error: {$client->errCode}\n");
                }
                $sender = $client->send("shutdown");

                $n = 1;
                while ($result = $client->recv()) {
                    echo "第{$n}次接收到内容\n";
                    if ($result == 'SHUTDOWN') {
                        echo "服务器已正常关闭。bye~\n";
                        break;
                    } else {
                        echo "服务器尚在运行之中,Please Wait~\n";
                        break;
                    }
                    $n++;
                }
                $client->close();
            } catch (Exception $e) {
                echo "Exception Cached: " . $e->getMessage();
            }
            break;
        default:
            echo 'invalid option, you can use start and stop params.';
    }
}catch (\Exception $e){
    Log::out('swoole', '[异常处理]' . $e->getMessage());
}
